package com.star.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.star.security.context.TokenContextHolder;
import com.star.security.user.Users;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatis-plus自动填充字段处理器
 *
 * @author yangzj
 */
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_TIME = "createTime";
    private final static String CREATOR = "creator";
    private final static String UPDATE_TIME = "updateTime";
    private final static String UPDATER = "updater";
    private final static String DELETED = "deleted";

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        strictInsertFill(metaObject, CREATE_TIME, LocalDateTime.class, now);
        strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class, now);
        strictInsertFill(metaObject, DELETED, Integer.class, 0);
        Users user = this.getUser();
        if (user == null) {
            return;
        }
        Long id = user.getId();
        strictInsertFill(metaObject, CREATOR, Long.class, id);
        strictInsertFill(metaObject, UPDATER, Long.class, id);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时间
        LocalDateTime now = LocalDateTime.now();
        strictUpdateFill(metaObject, UPDATE_TIME, LocalDateTime.class, now);
        Users user = this.getUser();
        if (user == null) {
            return;
        }
        strictUpdateFill(metaObject, UPDATER, Long.class, user.getId());
    }

    /**
     * 获取用户
     *
     * @return {@link Users}
     */
    private Users getUser() {
        Object principal = TokenContextHolder.getPrincipal();
        if (principal == null) {
            return null;
        }
        return (Users) principal;
    }
}
